package com.cndw.kungfu.controller;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.cndw.kungfu.comm.AccessClose;
import com.cndw.kungfu.comm.tencent.LogFieldType;
import com.cndw.kungfu.comm.tencent.QQDC;
import com.cndw.kungfu.config.Constants;
import com.cndw.kungfu.config.ConstantsConfig;
import com.cndw.kungfu.config.ConstantsCore;
import com.cndw.kungfu.config.ConstantsDailyItem;
import com.cndw.kungfu.config.ConstantsDayIntKey;
import com.cndw.kungfu.config.ConstantsFruit;
import com.cndw.kungfu.config.ConstantsIntKey;
import com.cndw.kungfu.config.ConstantsLevel;
import com.cndw.kungfu.config.ConstantsLog;
import com.cndw.kungfu.config.ConstantsModel;
import com.cndw.kungfu.config.ConstantsRadio;
import com.cndw.kungfu.config.ConstantsTask;
import com.cndw.kungfu.config.GoodsEffectConfig;
import com.cndw.kungfu.domain.Goods;
import com.cndw.kungfu.domain.GoodsMode;
import com.cndw.kungfu.domain.Player;
import com.cndw.kungfu.domain.TaskMode;
import com.cndw.kungfu.domain.Title;
import com.cndw.kungfu.domain.Union;
import com.cndw.kungfu.domain.UnionMember;
import com.cndw.kungfu.domain.Vocation;
import com.cndw.kungfu.event.once.PlayerStateTask;
import com.cndw.kungfu.ext.Aes;
import com.cndw.kungfu.ext.IDCardCheck;
import com.cndw.kungfu.ext.LanguageLib;
import com.cndw.kungfu.ext.LogUtil;
import com.cndw.kungfu.ext.MD5;
import com.cndw.kungfu.ext.TimeProcesser;
import com.cndw.kungfu.ext.WordProcesser;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.CrossProxySerialize;
import com.cndw.kungfu.model.DataSerialize;
import com.cndw.kungfu.model.DataStaticDay;
import com.cndw.kungfu.model.activity.domain.WorldBoos;
import com.cndw.kungfu.model.activity.holiday.HalloweenCore;
import com.cndw.kungfu.model.general.RankingListManager;
import com.cndw.kungfu.model.goods.PlayerBoxs;
import com.cndw.kungfu.model.goods.domain.ModeGoodsStarSuit;
import com.cndw.kungfu.model.goods.domain.SysModeAwards;
import com.cndw.kungfu.model.player.FormulaMarry;
import com.cndw.kungfu.model.player.FormulaScore;
import com.cndw.kungfu.model.player.PlayerManager;
import com.cndw.kungfu.model.player.domain.Dragon;
import com.cndw.kungfu.model.player.domain.Office;
import com.cndw.kungfu.model.pve.CityDefensesBattle;
import com.cndw.kungfu.model.siege.domain.SiegeWar;
import com.cndw.kungfu.model.sys.LogServer;
import com.cndw.kungfu.model.union.UnionManager;
import com.cndw.kungfu.vo.EventNotice;
import com.cndw.kungfu.vo.PlayerChangeVO;
import com.cndw.kungfu.vo.PrestigeVO;
import com.cndw.kungfu.vo.goodsvo.GoodsVO;
import com.cndw.kungfu.vo.rankingvo.PlayerRankingVO;
import com.cndw.rpg.annotation.Controller;
import com.cndw.rpg.framework.ResponseMessage;
import com.cndw.rpg.framework.Session;

/**
 * 人物处理
 * 
 * @author fantadust
 * 
 */
@Controller
public class PlayerController {

	@Autowired
	private PlayerManager playerManager;

	@Autowired
	private UnionManager unionManager;

	@Autowired
	private RankingListManager rankingListManager;

	/**
	 * 第一次登录加载的公共数据
	 * 
	 * @param session
	 * @return 技能模型 我的技能 我的好友id
	 */
	public ResponseMessage loadAtFirst(Session session) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		final int currentTime = TimeProcesser.getUnixTime();

		Map<String, Object> map = new HashMap<String, Object>();

		map.put("friendIds", player.getDataInfo().getFriendIds());
		map.put("mainTaskId", player.getDataInfo().getMainTaskId());
		map.put("lastStoryId", player.getDataInfo().getLastStoryId());
		map.put("accountName", player.getAccountName());
		map.put("bossDead", WorldBoos.getLastDead());// boss战已死亡
		map.put("costTips", player.getDataInfo().intDataGet(ConstantsIntKey.costTips));
		map.put("carFree", ConstantsModel.carnivalFree - player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.carFree));
		map.put("treeFree", ConstantsFruit.fruitDayMax - player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.fruit));
		if ((player.getDataInfo().intDataGet(ConstantsIntKey.comm) & 1 << 0) > 0) {
			map.put("cLink", 1);
		}
		if (player.getDataInfo().intDataGet(ConstantsIntKey.yelAct) != ConstantsCore.yelGotSign) {
			map.put("yelAct", true);
		}
		if (CityDefensesBattle.isSignDoing()) {// 襄阳保卫战进行中
			map.put("cityBattle", true);
		}
		if (SiegeWar.getCurrentMonster() != null) {// 帮派战是否还在进行
			map.put("siegeWar", true);
		}
		if (ConstantsConfig.getSysCgAtivity() > 0) {// 活动图标控制
			map.put("cgActivity", ConstantsConfig.getSysCgAtivity());
		}
		boolean hiddenOpenIcon = player.getDataInfo().intDataGet(ConstantsIntKey.aEquip) == 11
				&& player.getDataInfo().intDataGet(ConstantsIntKey.aDisTrain) == 6 && currentTime >= ConstantsConfig.getSysCgOpenTime() + 14 * 86400;
		int iconHD = hiddenOpenIcon ? 1 : 0;
		boolean hideUpAwardIcon = player.getDataInfo().intDataGet(ConstantsIntKey.upa) >= 6;
		iconHD = hideUpAwardIcon ? iconHD | 2 : iconHD;// 隐藏冲级活动图标
		if (iconHD > 0) {// 后续高于图标的隐藏放在这里
			map.put("iconHD", iconHD);
		}

		int payCash = player.getDataInfo().intDataGet(ConstantsIntKey.payCash);
		if (payCash > 0) {
			map.put("payCash", payCash);// 充值额度
		}

		if (player.getTitleId() > 0) {
			map.put("title", player.getTitleId());// 当前的称号
		}

		
		int hd = CrossProxySerialize.getInstance().worldHidGet(session.getUid());// 当前的头衔
		if (hd > 0) {
			map.put("hd", hd);
		}
		int gj = player.getDataInfo().intDataGet(ConstantsIntKey.gj);
		if (gj > 0) {
			map.put("gj", gj);
		}
		if (player.getDataInfo().getPet() != null) {
			map.put("ps", player.getDataInfo().getPet().getModeId());
			map.put("pn", player.getDataInfo().getPet().getName());
		}
		int tbs = HalloweenCore.getTBS(player.getPlayerId());
		if (tbs > 0) {
			map.put("tbs", tbs);
			map.put("tbt", HalloweenCore.getTBT(player.getPlayerId()));
		}
		if (player.getKnightTrueLevel() >= 2) {// 小飞鞋的个数
			map.put("freeTel", player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.freeTel));
		}
		if (player.getKnightTrueLevel() >= 2) {
			map.put("vipAward", player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.vipAward));
		}
		if (player.getDataInfo().getYLevel() > 0) {// 黄钻
			map.put("yLevel", player.getDataInfo().getYLevel());
			map.put("YYear", player.getDataInfo().isYYear());
			boolean noAward = player.getDataInfo().intDataGet(ConstantsIntKey.yelPrize) == 3
					&& player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.yelDPrize) > 0
					&& player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.yelSalary) > 0;
			if (noAward) {
				map.put("yAward", noAward);// 黄钻礼包全部领取了
			}
		}
		if (player.getDataInfo().getLv3() > 0) {
			map.put("lv3", player.getDataInfo().getLv3());
		}
		if (player.getDataInfo().intDataGet(ConstantsIntKey.aPayFirst) == 0) {
			map.put("apf", true);// 是否领取过首充礼包
		}
		if (player.getLevel() < ConstantsModel.friendCongLevel[1] || player.getDataInfo().intDataGet(ConstantsIntKey.expbox) > 0) {
			map.put("fe", ConstantsModel.friendCongMax - player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.friendzf));
		}
		if (player.getDataInfo().isGoodsLock()) {
			map.put("goodsLock", true);// 物品是否锁定
		}
		int awardSign = player.getDataInfo().intDataGet(ConstantsIntKey.aDayLogin);
		// LogUtil.getMain().debug(awardSign);
		if (awardSign < 3) {
			map.put("dayLogin", awardSign + 1);
			map.put("dayGet", player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.aDays));
		}
		if (player.getDataInfo().getEveryDay().getPveBug() >= ConstantsModel.wgBattleErrNum) {
			map.put("captcha", true);// 是否要验证码
		}

		int inviteNum = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.invite);
		if (inviteNum <= ConstantsModel.qqInviteNum) {// 邀请好友的个数
			map.put("invite", inviteNum);
		}
		map.put("bn", player.getDataInfo().getEveryDay().getBattleNum());// 今日战斗次数
		if (player.getExpJar() > 0) {
			map.put("expJar", player.getExpJar());
		}
		if (DataStaticDay.getInstance().isLoser(player.getLevel())) {// 世界经验的buff
			map.put("expBuff", 1);
		}
		if (player.getLevel() >= ConstantsLevel.lv50Dragon) {
			map.put("dpn", player.getDataInfo().intDataGet(ConstantsIntKey.pn));
			map.put("df", ConstantsModel.dragonDrawFreeMax - player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.drf));
		}

		if (player.getUnionId() > 0) {
			try {
				Union union = Context.getUnionServer().getUnionById(player.getUnionId());
				UnionMember member = union.getMember(player.getPlayerId());
				int permission = ConstantsConfig.getUnionJobsFlag()[member.getPosition()];
				map.put("unionName", union.getName());
				map.put("unLevel", union.getLevel());
				map.put("flag", member.getFlag());
				map.put("permission", permission);

			} catch (Exception e) {
				LogUtil.getMain().debug("err union " + session.getAccountName());
			}

		}

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 显示人物属性
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage show(Session session, long tagetId) {
		Map<String, Object> map = new HashMap<String, Object>();
		Player target = Context.getPlayerServer().getByPlayerId(tagetId <= 0 ? session.getUid() : tagetId);
		if (target == null) {
			return null;
		}
		Collection<Goods> equipGoods = target.getPlayerBoxs().getEquipList();
		List<GoodsVO> equipVOList = new ArrayList<GoodsVO>();
		for (Goods e : equipGoods) {
			equipVOList.add(e.toGoodsVO());
		}
		if (tagetId == session.getUid()) {
			map.put("otherPlayer", target.toPlayerVO());
		} else {
			map.put("otherPlayer", target.toOtherPlayerVO());
		}
		if (target.getDataInfo().getMlId() > 0 ){
			Player marry = Context.getPlayerServer().getByPlayerId(target.getDataInfo().getMlId());
			if (marry != null) {
				map.put("marryId", marry.getPlayerId());
				map.put("marryName", marry.getPlayerName());
			}
		}
	
		int officeLv = target.getDataInfo().intDataGet(ConstantsIntKey.office); 
		int xl = target.getDataInfo().intDataGet(ConstantsIntKey.xl);	
		int lw = target.getDataInfo().intDataGet(ConstantsIntKey.lw);
		
		map.put("equipList", equipVOList);
		map.put("fhfv", target.getDataInfo().intDataGet(ConstantsIntKey.fhfv));
		map.put("goodsStarSuit", ModeGoodsStarSuit.getStarSuite(equipGoods));
		Union union = Context.getUnionServer().getUnionById(target.getUnionId());
		map.put("unionName", union == null ? null : union.getName());
		map.put("challengeRanking", DataSerialize.getInstance().getChallengeData().getOrder(target.getPlayerId()));
		map.put("lw", lw);
		try{
			if (lw>0){
				map.put("lwAdd", Dragon.getOne(lw).getAddsVar());//龙纹
			}
			if(xl>0) {
				map.put("xlAdd",FormulaMarry.getAddv(xl));//侠侣
			}
			if (officeLv>0){
				map.put("officeAdd", Office.getOne(officeLv).getHurtCoff());//官职
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
		return ResponseMessage.getSuccMessage(map);

	}

	/**
	 * 显示声望
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage showPrestige(Session session) {
		long playerId = session.getUid();
		Map<String, Object> map = new HashMap<String, Object>();
		Player player = Context.getPlayerServer().getByPlayerId(playerId);

		Map<Integer, Object> tmpMap = new HashMap<Integer, Object>(3);

		for (int sceneId = 2; sceneId <= 4; sceneId++) {
			int currentPrestige = player.getDataInfo().getPrestige(sceneId);
			tmpMap.put(sceneId, PrestigeVO.getVO(currentPrestige));
		}

		map.put("prestige", tmpMap);

		int laveTimes = Context.getTaskServer().getTaskLaveTimes(playerId, TaskMode.typePrestige);
		map.put("laveTimes", laveTimes);

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 批量加点
	 * 
	 * @param session
	 * @param pointMap
	 * @return
	 */
	@Deprecated
	public ResponseMessage addPoint(Session session, Map<String, Integer> pointMap) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (session.getUid() > 0) {
			return null;
		}

		if (!pointMap.containsKey("power") || !pointMap.containsKey("physical") || !pointMap.containsKey("agile") || !pointMap.containsKey("wit")) {
			return null;
		}
		int power = pointMap.get("power");
		int physical = pointMap.get("physical");
		int agile = pointMap.get("agile");
		int wit = pointMap.get("wit");
		if (power < 0 || physical < 0 || agile < 0 || wit < 0)
			return null;
		int totalPoint = power + physical + agile + wit;
		synchronized (player) {
			if (player.getFreePoint() < totalPoint) {
				return null;// 溢出
			}

			player.alterPower(power);
			player.alterPhysical(physical);
			player.alterAgile(agile);
			player.alterWit(wit);
		}

		/**
		 * 属性联动
		 */
		Context.getPlayerServer().clacProperties(player);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("player", player.toPlayerVO());
		player.commitSync();// 提交同步
		return ResponseMessage.getSuccMessage(map);

	}

	/**
	 * 洗点
	 * 
	 * @param session
	 * @return
	 */
	@Deprecated
	public ResponseMessage resetPoint(Session session) {
		if (session.getUid() > 0) {
			return null;
		}
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Vocation vocation = Context.getCongfigServer().getVocation(player.getVocationId());
		if (player.getLevel() < 20) {
			return null;
		}
		PlayerBoxs playerBoxs = player.getPlayerBoxs();
		if (playerBoxs.getStackNum(GoodsEffectConfig.getPlayerresetpointgoodsid()) < 1) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("player.point.errgoods"));
		}
		playerBoxs.costGoods(GoodsEffectConfig.getPlayerresetpointgoodsid(), 1);

		int otherPonint = player.getLevel() - 1;

		player.setPower(vocation.getPower() + otherPonint + 18 * vocation.getAddPower());
		player.setWit(vocation.getWit() + otherPonint + 18 * vocation.getAddWit());
		player.setAgile(vocation.getAgile() + otherPonint + 18 * vocation.getAddAgile());
		player.setPhysical(vocation.getPhysical() + otherPonint + 18 * vocation.getAddPhysical());

		Context.getPlayerServer().clacProperties(player);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("player", player.toPlayerVO());
		player.commitSync();// 提交同步

		// 添加“人物-洗点”日志
		LogServer.recordLog(player, ConstantsLog.player, 30004, player.getPower(), player.getPhysical(), player.getAgile(), player.getWit());

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 搜索好友id
	 * 
	 * @param playerName
	 * @return
	 */
	public ResponseMessage searchPlayer(Session session, String playerName) {

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("playerId", Context.getPlayerServer().getPlayerId(playerName));

		return ResponseMessage.getSuccMessage(map);

	}

	/**
	 * 领取新手时间礼包
	 * 
	 * @param session
	 * @param times
	 * @return
	 */
	public ResponseMessage noviceOnlineAward(Session session, int times) {
		int[] awardTimes = ConstantsModel.playerNoviceAwardTimes;
		long playerId = session.getUid();
		Player player = Context.getPlayerServer().getByPlayerId(playerId);
		if (times > awardTimes.length) {
			return null;
		}
		if (player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.timesNoviec) >= times) {
			return null;
		}
		int needLineTime = awardTimes[times - 1];// 领取所需要时间
		int begingTime = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.noviecAward);
		begingTime = begingTime == 0 ? TimeProcesser.getUnixTime() : begingTime;

		int haveOnLineTime = TimeProcesser.getUnixTime() - begingTime;// 在线时长
		if (haveOnLineTime < needLineTime) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("player.novice.errtime"));
		}

		SysModeAwards awards = SysModeAwards.get(100, times);
		if (awards == null) {
			return null;
		}
		StringBuffer logSB = new StringBuffer();
		if (awards.getSubPopsList() != null) {
			// int needSize = awards.getSubPopsList().size();
			int needSize = Context.getGoodsServer().checkSubPopsBlack(awards.getSubPopsList());
			if (!player.getPlayerBoxs().checkBlack(needSize)) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.player.boxmin", needSize));
			}
			Context.getGoodsServer().giveSubPops(awards.getSubPopsList(), player, logSB);
		}
		player.getDataInfo().getEveryDay().intDataSet(ConstantsDayIntKey.timesNoviec, times);
		player.getDataInfo().getEveryDay().intDataSet(ConstantsDayIntKey.noviecAward, TimeProcesser.getUnixTime());

		Map<String, Object> map = new HashMap<String, Object>();
		if (times < awardTimes.length) {
			map.put("nextTime", awardTimes[times]);
			int nextTime = times + 1;
			map.put("nextAwardId", nextTime);
			map.put("awardTips", "");
		}
		map.put("suc", true);

		// 添加"人物-领取新手时间礼包"日志
		LogServer.recordLog(player, ConstantsLog.player, 30006, logSB.toString());
		QQDC.getInstance().logClick(player, LogFieldType.awardTime);

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 领取vip回馈礼包
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage vipAward(Session session) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getKnightTrueLevel() <= 1) {
			return null;
		}
		if (player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.vipAward) > 0) {
			return null;
		}
		player.getDataInfo().getEveryDay().intDataSet(ConstantsDayIntKey.vipAward, TimeProcesser.getUnixTime());
		player.stateAdd(Constants.playerState32_vipAdd);
		Context.getPlayerServer().clacProperties(player);
		new PlayerStateTask(Constants.playerState32_vipAdd, 1800, player);

		return ResponseMessage.getSuccMessage(player.toPlayerVO());
	}

	/**
	 * 领取开服3日奖励
	 * 
	 * @param session
	 * @param days
	 * @return
	 */
	public ResponseMessage awardNewUser(Session session, int days) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		int awardSign = player.getDataInfo().intDataGet(ConstantsIntKey.aDayLogin);
		if (awardSign >= 3) {
			return null;
		}
		if (player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.aDays) != 0) {
			return null;
		}
		// if (player.getTodayOnLine() <= 1800) {
		// return null;
		// }

		awardSign++;

		int awardId = awardSign;
		if (awardId >= 2) {
			awardId = awardSign * 10 + player.getVocationId();
		}

		SysModeAwards awards = SysModeAwards.get(125, awardId);
		if (awards == null) {
			return null;
		}
		StringBuffer logSB = new StringBuffer();
		if (awards.getSubPopsList() != null) {
			int needSize = Context.getGoodsServer().checkSubPopsBlack(awards.getSubPopsList());
			if (!player.getPlayerBoxs().checkBlack(needSize)) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.player.boxmin", needSize));
			}
			Context.getGoodsServer().giveSubPops(awards.getSubPopsList(), player, logSB);
		}
		player.getDataInfo().getEveryDay().intDataSet(ConstantsDayIntKey.aDays, 1);
		player.getDataInfo().intDataSet(ConstantsIntKey.aDayLogin, awardSign);
		player.getDataInfo().commitSync();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("awardSign", awardSign);

		// 添加"人物-领取新手时间礼包"日志
		LogServer.recordLog(player, ConstantsLog.player, 30201, logSB.toString());
		QQDC.getInstance().logClick(player, LogFieldType.awardDayThree);

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 获取玩家嗑药详情
	 * 
	 * @param session
	 * @return map key:丹药goodsId value:数量
	 */
	public ResponseMessage showDrugs(Session session) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getLevel() < ConstantsLevel.lv30Drug[0]) {
			return null;
		}
		Map<Integer, Integer> drugsMap = player.getDataInfo().getDrugsMap();
		return ResponseMessage.getSuccMessage(drugsMap);
	}

	/**
	 * 玩家嗑药
	 * 
	 * @param session
	 * @param goodsId
	 *            丹药goodsId
	 * @param num
	 *            丹药数量
	 * @return
	 */
	public ResponseMessage takeDrug(Session session, int goodsId, int num) {
		long playerId = session.getUid();
		Player player = Context.getPlayerServer().getByPlayerId(playerId);
		GoodsMode goodsMode = Context.getGoodsServer().getModeById(goodsId);

		if (goodsMode == null || num <= 0 || goodsMode.getAppId() != ConstantsModel.drugAppId) {
			return null;
		}

		PlayerBoxs playerBoxs = Context.getGoodsServer().getPlayerBoxs(playerId);

		if (playerBoxs.getStackNum(goodsId) < num) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("drug.takedrug.druglack"));
		}

		if (player.getLevel() < goodsMode.getPlayerLevel()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("drugs.takedrug.neellevel"));
		}

		// 求的丹药等级
		int drugStage = 0;// 丹药等级 0初级 1中级 2高级
		for (int i = 0; i < ConstantsLevel.lv30Drug.length; i++) {
			if (goodsMode.getPlayerLevel() >= ConstantsLevel.lv30Drug[i]) {
				drugStage = i;
			}
		}

		// 1 命中 2闪避 3暴击 4 韧性 5攻击 6防御 7生命 8魔法 9速度
		int drugType = goodsMode.getValueA();
		// 嗑药次数
		int takeNum = player.getDataInfo().getDrugNum(goodsId);
		if (takeNum + num > ConstantsModel.drugTakeNumLimit[drugStage]) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("drugs.takedrug.takenumlimit", ConstantsModel.drugTakeNumLimit[drugStage]));
		}

		playerBoxs.costGoods(goodsId, num);
		int takeAmount = player.getDataInfo().increaseDrugNum(goodsId, num);
		// 增加的属性值
		int attriAdd = goodsMode.getValueB() * num;
		player.getDataInfo().increaseDrugsAdd(drugType, attriAdd);
		player.commitSync();
		player.getDataInfo().commitSync();

		Context.getPlayerServer().clacProperties(player);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("player", player.toPlayerVO());

		LogServer.recordLog(player, ConstantsLog.player, 30007, goodsMode.getName(), num, attriAdd, drugStage, ConstantsModel.drugTakeNumLimit[drugStage]
				- takeAmount);

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 填写防沉迷
	 * 
	 * @param session
	 * @param realName
	 * @param cardId
	 * @return
	 */
	public ResponseMessage writeAddicted(Session session, String realName, String cardId) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getDataInfo().isPassAddicted()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("player.idcard.pass"));
		}

		if (!IDCardCheck.IdCardValidate(cardId)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("player.idcard.err"));
		}

		if (Context.getPlayerServer().registerPlayerIdCard(session.getUid(), realName, cardId)) {
			player.getDataInfo().setPassAddicted(true);
			return ResponseMessage.getSuccMessage(true);
		} else {
			return ResponseMessage.getSuccMessage(false);
		}
	}

	/**
	 * 状态标记
	 * 
	 * @param session
	 * @param state
	 * @param add
	 * @return
	 */
	public ResponseMessage signState(Session session, int state, boolean add) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (state == Constants.playerState512_battleAuto) {

			if (add) {
				player.getDataInfo().getEveryDay().finishDailyItem(ConstantsDailyItem.autoFightingItem);
				player.stateAdd(state);

				Context.getTaskServer().notifyToSpark(session.getUid(), ConstantsTask.spark33Ai, 1);

			} else {
				player.stateRemove(state);
			}

		} else if (state == Constants.playerState2048_closeSound) {
			if (add) {
				player.stateAdd(state);
			} else {
				player.stateRemove(state);
			}
		}

		return null;
	}

	/**
	 * 消费项目提示设置
	 * 
	 * @param session
	 * @param state
	 * @return
	 */
	public ResponseMessage costTips(Session session, int state) {
		if (state < 0) {
			return null;
		}
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());

		player.getDataInfo().intDataSet(ConstantsIntKey.costTips, state);
		player.getDataInfo().commitSync();
		return ResponseMessage.getSuccMessage(player.getDataInfo().intDataGet(ConstantsIntKey.costTips));
	}

	/**
	 * 获取称号信息
	 * 
	 * @param getUsed
	 *            true 获取已使用的称号 false 不获取已经用的称号
	 * @param type
	 *            0全部 1成长 2 装备 3徒弟 4宠物 5社交 6声望 7神兵阵 8答题 9排行榜
	 * @return
	 */
	public ResponseMessage showTitles(Session session, boolean getUsed, int type) {
		long playerId = session.getUid();
		Player player = Context.getPlayerServer().getByPlayerId(playerId);
		if (player.getLevel() < ConstantsLevel.lv08Title) {
			return ResponseMessage.errMsg(LanguageLib.get("comm.err.args"));
		}
		int titleId = player.getTitleId();
		Map<String, Object> map = new HashMap<String, Object>();
		if (getUsed) {

			if (titleId > 0) {
				Title title = Context.getCacheCenter().getTitle(titleId);
				if (title != null) {
					map.put("titleId", titleId);
					map.put("name", title.getTitleName());
					map.put("quality", title.getQuality());
					map.put("addAttri", title.getAddAttri());
				}

			}
		}

		List<Title> titles = new LinkedList<Title>();
		if (type == 0) {
			titles.addAll(Context.getCacheCenter().getAllTitles());
		} else if (type == 1) {
			titles.addAll(Context.getCacheCenter().getTitles(Constants.titleLevelUp));
		} else if (type == 2) {
			titles.addAll(Context.getCacheCenter().getTitles(Constants.titleUpStar));
		} else if (type == 3) {
			titles.addAll(Context.getCacheCenter().getTitles(Constants.titleDiscipleRein));
		} else if (type == 4) {
			// 屏蔽宠物称号
			// titles.addAll(Context.getCacheCenter().getTitles(Constants.titlePet));
		} else if (type == 5) {
			// titles.addAll(Context.getCacheCenter().getTitles(Constants.titleFriend));
		} else if (type == 6) {
			// titles.addAll(Context.getCacheCenter().getTitles(Constants.titlePrestige));
		} else if (type == 7) {
			titles.addAll(Context.getCacheCenter().getTitles(Constants.titleSCpPass));
		} else if (type == 8) {
			titles.addAll(Context.getCacheCenter().getTitles(Constants.titleQuiz));
		} else if (type == 9) {
			titles.addAll(Context.getCacheCenter().getTitles(Constants.titleLevelRanking));
			titles.addAll(Context.getCacheCenter().getTitles(Constants.titleAttackRanking));
			// 屏蔽宝鉴称号
			// titles.addAll(Context.getCacheCenter().getTitles(Constants.titleCollectRanking));
			titles.addAll(Context.getCacheCenter().getTitles(Constants.titleDiscipleRanking));
			titles.addAll(Context.getCacheCenter().getTitles(Constants.titleSCpRanking));
			titles.addAll(Context.getCacheCenter().getTitles(Constants.titleUnionRanking));
		} else {
			titles.addAll(Context.getCacheCenter().getTitles(type));
		}

		if (titles != null) {
			List<Map<String, Object>> titleList = new LinkedList<Map<String, Object>>();
			for (Title title : titles) {
				if ( title.getHide() != 0) {
					continue;
				}
				Map<String, Object> tempMap = new HashMap<String, Object>();
				tempMap.put("titleId", title.getId());
				tempMap.put("name", title.getTitleName());
				tempMap.put("quality", title.getQuality());
				tempMap.put("get", Context.getGeneralServer().hasTitle(playerId, title.getId()));
				tempMap.put("describe", title.getDescri());
				tempMap.put("addAttri", title.getAddAttri());
				titleList.add(tempMap);
			}
			map.put("titles", titleList);
		}

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 使用/卸下称号
	 * 
	 * @param session
	 * @param use
	 *            true 使用 false 卸下
	 * @return
	 */
	public ResponseMessage useTitle(Session session, boolean use, int titleId) {
		long playerId = session.getUid();
		Player player = Context.getPlayerServer().getByPlayerId(playerId);
		if (player.getLevel() < ConstantsLevel.lv08Title) {
			return ResponseMessage.errMsg(LanguageLib.get("comm.err.args"));
		}

		Title title = Context.getCacheCenter().getTitle(titleId);
		if (title == null) {
			return ResponseMessage.errMsg(LanguageLib.get("comm.err.args"));
		}

		if (!Context.getGeneralServer().hasTitle(playerId, titleId)) {
			return ResponseMessage.errMsg(LanguageLib.get("comm.err.args"));
		}

		EventNotice eNotice = new EventNotice(ConstantsRadio.title, ConstantsRadio.titleUse);
		if (use) {
			player.setTitleId(titleId);
			eNotice.put("titleId", titleId);
			eNotice.put("on", true);
		} else {
			player.setTitleId(0);
			eNotice.put("on", false);
		}
		player.commitSync();
		Context.getPlayerServer().clacProperties(player);

		Context.getTaskServer().notifyToSpark(session.getUid(), ConstantsTask.spark29UseTitle, 1);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("titleId", titleId);
		map.put("playerVO", player.toPlayerVO());

		eNotice.put("playerId", playerId);
		eNotice.put("tdo", false);// 自己不处理
		eNotice.broadcastScene(player.getSceneId(), player.getSubLine());

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 修改名字
	 * 
	 * @param session
	 * @param namenew
	 * @return
	 */
	public ResponseMessage changeName(Session session, String namenew) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		int goodsId = 103501;// 113501=更名贴
		if (!player.getPlayerBoxs().isHaveGoods(goodsId)) {
			return null;
		}

		// 这里要检测是否已创建
		if (StringUtils.isBlank(namenew)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("login.needUserName"));
		}
		int nameLength = namenew.getBytes(Constants.charset).length;
		if (nameLength < ConstantsConfig.getNameLength() || nameLength > ConstantsConfig.getNameLengthMax()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("login.nameLengthErr", ConstantsConfig.getNameLength(), ConstantsConfig.getNameLengthMax()));
		} else if (!WordProcesser.chkPerg(namenew, ConstantsConfig.getCommCreateNameExp())) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("login.nameReg"));
		} else if (WordProcesser.chkBadWorlds(namenew) != null) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("login.nameReg"));
		}

		if (playerManager.getPlayerIdByPlayerName(namenew) > 0) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("login.overreg"));
		}
		player.setPlayerName(namenew);
		player.commitSync();
		player.getPlayerBoxs().costGoods(goodsId, 1);
		// 修改好友数据库里面的名称
		Context.getPlayerServer().updateFriendName(session.getUid(), namenew);
		if (player.getUnionId() > 0) {
			Union union = Context.getUnionServer().getUnionById(player.getUnionId());
			if (union != null && union.getPlayerId() == player.getPlayerId()) {
				union.setPlayerName(namenew);
				unionManager.updateUnionPlayerName(union);
			}
		}

		rankingListManager.changePlayerName(player.getPlayerId(), namenew);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("namenew", namenew);
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 显示我的挂机界面
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage agentShow(Session session) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("agent", player.getAgent());

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 设置替身娃娃的属性
	 * 
	 * @param session
	 * @param openState
	 * @return
	 */
	@AccessClose
	public ResponseMessage agentConfig(Session session, int type, boolean open) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		player.setAgent(0);
		player.commitSync();

		return ResponseMessage.getSuccMessage(player.getAgent());
	}

	/**
	 * 把经验封装起来
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage jarExp(Session session, long costExpObj) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player == null) {
			return null;
		}
		if (player.getLevel() < 50) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("player.exp.jarlevel"));
		}else if (costExpObj >= Integer.MAX_VALUE) {
			return null;
		}
		int costExp = Integer.valueOf(String.valueOf(costExpObj));
		if (costExp > player.getExp() || costExp <= 0) {
			return null;
		}
		// if (player.getExpJar() >= Integer.MAX_VALUE - costExp) {
		// return null;// 整形溢出控制
		// }
		synchronized (player) {
			player.alterExp(-costExp);
			player.alterExpJar(costExp);
		}
		player.commitSync();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("exp", player.getExp());
		map.put("expJar", player.getExpJar());
		map.put("jar", costExp);

		LogServer.recordLog(player, ConstantsLog.player, 30302, costExp, player.getExpJar());

		return ResponseMessage.getSuccMessage(map);
	}

	public ResponseMessage lockShow(Session session) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("havePass", player.getDataInfo().getLockPass() != null);
		map.put("unLockTime", player.getDataInfo().intDataGet(ConstantsIntKey.passUnLock));
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 设置或修改密码
	 * 
	 * @param session
	 * @param oldPass
	 * @param pass1
	 * @param pass2
	 * @return
	 */
	public ResponseMessage lockPassword(Session session, String oldPass, String pass1, String pass2) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());

		if (player.getDataInfo().getLockPass() != null) {
			if (oldPass == null || oldPass.length() == 0) {
				return null;
			}
			if (MD5.compile16(oldPass).equals(player.getDataInfo().getLockPass()) == false) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("player.pass.errold"));
			}
		}
		if (pass1 == null || pass1 == null || !pass1.equals(pass2)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("player.pass.errtime"));
		}
		String logPass = null;
		if (pass1.length() == 0 || pass1.equals("") || pass1.equals("null")) {
			player.getDataInfo().setLockPass(null);
		} else {
			if (pass1.length() < 4 || pass1.length() > 10) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("player.pass.length"));
			}
			logPass = Aes.encrypt(pass1, "linzi9677889");
			player.getDataInfo().setLockPass(MD5.compile16(pass1));
		}
		player.getDataInfo().setOpenPass(true);
		player.getDataInfo().intDataRemove(ConstantsIntKey.passUnLock);
		LogServer.recordLog(player, ConstantsLog.player, 30101, logPass);
		return ResponseMessage.getSuccMessage(player.getDataInfo().getLockPass() != null);
	}

	/**
	 * 输入密码打开交易
	 * 
	 * @param session
	 * @param passworld
	 * @return
	 */
	public ResponseMessage lockOpen(Session session, String passworld) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getDataInfo().getLockPass() == null) {
			return ResponseMessage.ticpMsg(LanguageLib.get("player.pass.noset"));
		}
		if (passworld == null || passworld.length() == 0) {
			return ResponseMessage.getFailMessage(false);
		}
		if (!MD5.compile16(passworld).equals(player.getDataInfo().getLockPass())) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("player.pass.err"));
		}
		player.getDataInfo().setOpenPass(true);
		return ResponseMessage.getSuccMessage(true);
	}

	/**
	 * 强制解锁的开关
	 * 
	 * @param session
	 * @param open
	 * @return
	 */
	public ResponseMessage lockUnlock(Session session, boolean open) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getDataInfo().getLockPass() == null) {
			return ResponseMessage.ticpMsg(LanguageLib.get("player.pass.noset"));
		}
		if (open) {
			player.getDataInfo().intDataSet(ConstantsIntKey.passUnLock, TimeProcesser.getUnixTime() + 3 * 86400);
		} else {
			player.getDataInfo().intDataRemove(ConstantsIntKey.passUnLock);
		}
		player.getDataInfo().commitSync();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("unLockTime", player.getDataInfo().intDataGet(ConstantsIntKey.passUnLock));
		LogServer.recordLog(player, ConstantsLog.player, 30102, open);
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 显示玩家战力
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage powerDetail(Session session) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		int oldScore = player.getScore();
		int[][] power = FormulaScore.calcAllScore(player);

		PlayerRankingVO ranking = Context.getGeneralServer().getPlayerRanking(player);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("power", power);
		map.put("powerRank", ranking.getAttackRank());
		if (oldScore != power[0][0]) {
			player.setScore(power[0][0]);
			Context.getPlayerServer().change(PlayerChangeVO.PLAYER_MAIN, player.toPlayerVO(), player.getPlayerId());
		}

		int officeLv = player.getDataInfo().intDataGet(ConstantsIntKey.office);
		map.put("officeName", Office.getOne(officeLv) != null ? Office.getOne(officeLv).getTitle() : null);
		map.put("color", Office.getOne(officeLv) != null ? Office.getOne(officeLv).getColor() : 0);
		map.put("hurtCoff", Office.getOne(officeLv) != null ? Office.getOne(officeLv).getHurtCoff() : 0);
		map.put("curAchive", player.getDataInfo().intDataGet(ConstantsIntKey.achv));

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 显示玩家官职信息
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage officeShow(Session session) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getLevel() < ConstantsLevel.lv30Office) {
			return null;
		}

		Office.deAchive(player);

		int officeLv = player.getDataInfo().intDataGet(ConstantsIntKey.office);
		int curAchive = player.getDataInfo().intDataGet(ConstantsIntKey.achv);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("curOffice", Office.getOne(officeLv));
		map.put("nextOffice", Office.getOne(officeLv + 1));
		map.put("curAchive", curAchive);
		map.put("salaryGet", player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.salary));

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 领取俸禄
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage getSalary(Session session) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		int officeLv = player.getDataInfo().intDataGet(ConstantsIntKey.office);
		if (officeLv <= 0) {
			return null;
		}
		Office.deAchive(player);

		boolean haveGet = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.salary) > 0;
		if (haveGet) {
			return null;
		}
		int getAsset = Office.getSalaryByLv(officeLv);
		player.alterAsset(getAsset);
		player.commitSync();

		player.getDataInfo().getEveryDay().intDataSet(ConstantsDayIntKey.salary, 1);
		// 设置到每日奖励
		player.getDataInfo().getEveryDay().finishDailyItem(ConstantsDailyItem.getDailySalaryItem);
		player.getDataInfo().commitSync();
		LogServer.recordLog(player, ConstantsLog.player, 30403, Office.getSalaryByLv(officeLv), player.getAsset());

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("asset", player.getAsset());
		map.put("getAsset", getAsset);
		map.put("salaryGet", player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.salary));
		return ResponseMessage.getSuccMessage(map);
	}

	public ResponseMessage gjShow(Session session) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("gj", player.getDataInfo().intDataGet(ConstantsIntKey.gj));
		map.put("g", player.getDataInfo().intDataGet(ConstantsIntKey.g));
		return ResponseMessage.getSuccMessage(map);
	}

	public ResponseMessage gjUse(Session session, int gj) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		int g = player.getDataInfo().intDataGet(ConstantsIntKey.g);
		if ((g & gj) <= 0 && gj > 0) {
			return null;
		}
		if (gj > 1 && gj % 2 == 1) {
			return null;
		}
		EventNotice eventNotice = new EventNotice(ConstantsRadio.comm, ConstantsRadio.commGJChange);
		eventNotice.put("uid", player.getPlayerId());
		eventNotice.put("gj", gj);
		eventNotice.broadcastScene(player);
		// eventNotice.broadcast(session.getUid());

		player.getDataInfo().intDataSet(ConstantsIntKey.gj, gj);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("gj", player.getDataInfo().intDataGet(ConstantsIntKey.gj));
		map.put("g", g);
		return ResponseMessage.getSuccMessage(map);
	}

}
